package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl  implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) throws IOException {

        List<ApArticleSearch> articleSearchList = new ArrayList<>();
        // TODO 4.2 完成文章搜索，返回的数据是一个list集合
        if (StringUtils.isBlank(dto.getSearchWords())) {
            return null;
        }
        MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", dto.getSearchWords());
        PageRequest pageable = PageRequest.of(dto.getPage().intValue() - 1, dto.getSize(), Sort.by(Sort.Direction.DESC, "publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(queryBuilder, pageable);
        articleSearchList=searchPage.getContent();


        return ResponseResult.okResult(articleSearchList);


    }


}
